import { Button, Form, Space } from "antd";
import { IForm } from "@/components";
import { useState, useContext } from 'react'

import { SearchParam, SelectOptions } from "../type";
import type { FormItemConfig } from "@/components/FormItem";
import React from "react";
import { useAppSelector, useUserResources } from '@/utils/hooks'
import { Context } from '../index'
import request from "@/utils/request";
import AddModal from "./AddModal";

interface Props {
	options: SelectOptions;
	doSearch: (param: SearchParam) => void;
}

const SearchForm: React.FC<Props> = ({ doSearch ,options}) => {
	const [app] = useAppSelector(state => [state.app])
	const [addVisible, setAddVisible] = useState(false)

	const [form] = Form.useForm();
	const { total } = useContext(Context)


	const handleFinish = (value: SearchParam) => {
		const data = {
			...value
		};
		doSearch(data);
	};

	const handleClear = () => {
		form.resetFields();
	};

	const handleUpdateResult = () => {
		if (total > 5000) {
			// return message.error('一次只能导出5000条')
		}
		const data = {
			entityId: app.currentEntity.entityId,
			...form.getFieldsValue(),
		}

		request('userManageExportQueryResult', { data }).then(res => {
			if (res?.code === 0) {
				window.open(res.data)
			}
		})
	}

	const formItemsConfig: FormItemConfig[] = [
		{
			type: "input",
			formItemProps: {
				label: "课程编号",
				name: "courseNo"
			},
			childProps: {
				placeholder: "请输入课程编号"
			}
		},
		{
			type: "select",
			formItemProps: {
				label: "课程类型",
				name: "classifyId"
			},
			childProps: {
				placeholder: "请选择课程类型",
				options: options.classify
			}
		},
		{
			type: "select",
			formItemProps: {
				label: "学期",
				name: "termId"
			},
			childProps: {
				placeholder: "请选择学期",
				options: options.term
			}
		},
		{
			type: "select",
			formItemProps: {
				label: "状态",
				name: "status"
			},
			childProps: {
				placeholder: "请选择课程状态",
				options: [
					{ label: "开启", value: 1 },
					{ label: "关闭", value: 0 }
				]
			}
		},
		// {
		// 	type: "select",
		// 	formItemProps: {
		// 		label: "区域",
		// 		name: "companyId"
		// 	},
		// 	childProps: {
		// 		options: [
		// 			{ label: "1区", value: 1 },
		// 			{ label: "2区", value: 2 }
		// 		],
		// 		placeholder: "请选择区域"
		// 	}
		// },
	];

	return (
		<>
			<IForm form={form} formItemsConfig={formItemsConfig} onFinish={handleFinish} onClear={handleClear}></IForm>
			<Space className="mb20 mt12">
				<Button
					type="primary"
					onClick={() => {
						setAddVisible(true)
					}}
				>
					导入
				</Button>
				{addVisible && (
					<AddModal
						visible={addVisible}
						doSearch={doSearch}
						onCancel={() => setAddVisible(false)}
					></AddModal>
				)}
				<Button
					type="primary"
					onClick={() => {
						handleUpdateResult()
					}}
				>
					导出
				</Button>
			</Space>
		</>
	);
};

export default SearchForm;
